<template>
  <div class="api-test">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="test-card">
          <template #header>
            <div class="card-header">
              <span>API接口测试</span>
              <el-button type="primary" @click="sendRequest" :loading="loading">
                发送请求
              </el-button>
            </div>
          </template>
          
          <el-form :model="requestForm" label-width="100px" class="request-form">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="请求方法">
                  <el-select v-model="requestForm.method" placeholder="选择请求方法">
                    <el-option label="GET" value="GET" />
                    <el-option label="POST" value="POST" />
                    <el-option label="PUT" value="PUT" />
                    <el-option label="DELETE" value="DELETE" />
                    <el-option label="PATCH" value="PATCH" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="请求URL">
                  <el-input 
                    v-model="requestForm.url" 
                    placeholder="输入完整的API地址，例如: http://localhost:8080/api/users"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="请求头">
              <el-button @click="addHeader" type="text" icon="Plus">添加请求头</el-button>
              <div v-for="(header, index) in requestForm.headers" :key="index" class="header-item">
                <el-row :gutter="10">
                  <el-col :span="10">
                    <el-input v-model="header.key" placeholder="Header名称" />
                  </el-col>
                  <el-col :span="10">
                    <el-input v-model="header.value" placeholder="Header值" />
                  </el-col>
                  <el-col :span="4">
                    <el-button @click="removeHeader(index)" type="danger" icon="Delete" circle />
                  </el-col>
                </el-row>
              </div>
            </el-form-item>

            <el-form-item label="请求参数" v-if="requestForm.method === 'GET'">
              <el-button @click="addParam" type="text" icon="Plus">添加参数</el-button>
              <div v-for="(param, index) in requestForm.params" :key="index" class="param-item">
                <el-row :gutter="10">
                  <el-col :span="10">
                    <el-input v-model="param.key" placeholder="参数名称" />
                  </el-col>
                  <el-col :span="10">
                    <el-input v-model="param.value" placeholder="参数值" />
                  </el-col>
                  <el-col :span="4">
                    <el-button @click="removeParam(index)" type="danger" icon="Delete" circle />
                  </el-col>
                </el-row>
              </div>
            </el-form-item>

            <el-form-item label="请求体" v-if="['POST', 'PUT', 'PATCH'].includes(requestForm.method)">
              <el-radio-group v-model="requestForm.bodyType" class="body-type-group">
                <el-radio label="json">JSON</el-radio>
                <el-radio label="form">Form Data</el-radio>
                <el-radio label="raw">Raw Text</el-radio>
              </el-radio-group>
              
              <div v-if="requestForm.bodyType === 'json'" class="body-content">
                <el-input
                  v-model="requestForm.body"
                  type="textarea"
                  :rows="8"
                  placeholder="输入JSON格式的请求体"
                />
              </div>
              
              <div v-if="requestForm.bodyType === 'form'" class="body-content">
                <el-button @click="addFormField" type="text" icon="Plus">添加字段</el-button>
                <div v-for="(field, index) in requestForm.formFields" :key="index" class="form-field-item">
                  <el-row :gutter="10">
                    <el-col :span="10">
                      <el-input v-model="field.key" placeholder="字段名称" />
                    </el-col>
                    <el-col :span="10">
                      <el-input v-model="field.value" placeholder="字段值" />
                    </el-col>
                    <el-col :span="4">
                      <el-button @click="removeFormField(index)" type="danger" icon="Delete" circle />
                    </el-col>
                  </el-row>
                </div>
              </div>
              
              <div v-if="requestForm.bodyType === 'raw'" class="body-content">
                <el-input
                  v-model="requestForm.body"
                  type="textarea"
                  :rows="8"
                  placeholder="输入原始文本"
                />
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="response-card">
          <template #header>
            <div class="card-header">
              <span>响应结果</span>
              <el-tag v-if="responseStatus" :type="responseStatus >= 200 && responseStatus < 300 ? 'success' : 'danger'">
                {{ responseStatus }}
              </el-tag>
            </div>
          </template>
          
          <div v-if="response" class="response-content">
            <el-tabs v-model="activeTab" type="border-card">
              <el-tab-pane label="响应体" name="body">
                <div class="response-body">
                  <pre>{{ formatResponse(response.data) }}</pre>
                </div>
              </el-tab-pane>
              <el-tab-pane label="响应头" name="headers">
                <div class="response-headers">
                  <el-descriptions :column="1" border>
                    <el-descriptions-item 
                      v-for="(value, key) in response.headers" 
                      :key="key" 
                      :label="key"
                    >
                      {{ value }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </el-tab-pane>
              <el-tab-pane label="请求信息" name="request">
                <div class="request-info">
                  <el-descriptions :column="1" border>
                    <el-descriptions-item label="请求方法">{{ requestForm.method }}</el-descriptions-item>
                    <el-descriptions-item label="请求URL">{{ requestForm.url }}</el-descriptions-item>
                    <el-descriptions-item label="请求时间">{{ responseTime }}ms</el-descriptions-item>
                    <el-descriptions-item label="响应大小">{{ responseSize }}B</el-descriptions-item>
                  </el-descriptions>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
          
          <div v-else class="no-response">
            <el-empty description="暂无响应数据，请发送请求" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { sendHttpRequest } from '@/utils/api'

const loading = ref(false)
const response = ref(null)
const responseTime = ref(0)
const responseSize = ref(0)
const responseStatus = ref(null)
const activeTab = ref('body')

const requestForm = reactive({
  method: 'GET',
  url: '',
  headers: [
    { key: 'Content-Type', value: 'application/json' }
  ],
  params: [],
  bodyType: 'json',
  body: '',
  formFields: []
})

const addHeader = () => {
  requestForm.headers.push({ key: '', value: '' })
}

const removeHeader = (index) => {
  requestForm.headers.splice(index, 1)
}

const addParam = () => {
  requestForm.params.push({ key: '', value: '' })
}

const removeParam = (index) => {
  requestForm.params.splice(index, 1)
}

const addFormField = () => {
  requestForm.formFields.push({ key: '', value: '' })
}

const removeFormField = (index) => {
  requestForm.formFields.splice(index, 1)
}

const formatResponse = (data) => {
  try {
    return JSON.stringify(data, null, 2)
  } catch {
    return data
  }
}

const sendRequest = async () => {
  if (!requestForm.url) {
    ElMessage.error('请输入请求URL')
    return
  }

  loading.value = true
  const startTime = Date.now()

  try {
    const result = await sendHttpRequest(requestForm)
    response.value = result
    responseStatus.value = result.status
    responseTime.value = Date.now() - startTime
    responseSize.value = JSON.stringify(result.data).length
    
    ElMessage.success('请求发送成功')
  } catch (error) {
    ElMessage.error(`请求失败: ${error.message}`)
    response.value = null
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.api-test {
  max-width: 1200px;
  margin: 0 auto;
}

.test-card, .response-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.request-form {
  margin-top: 20px;
}

.header-item, .param-item, .form-field-item {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.body-type-group {
  margin-bottom: 15px;
}

.body-content {
  margin-top: 15px;
}

.response-content {
  min-height: 300px;
}

.response-body pre {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.response-headers, .request-info {
  padding: 20px 0;
}

.no-response {
  text-align: center;
  padding: 60px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .header-item, .param-item, .form-field-item {
    padding: 8px;
  }
}
</style>
